/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DutView.java
 *
 * Created on 05.Şub.2010, 09:27:43
 */
package org.testis.gui.mvc.view.testbed;

import org.testis.gui.mvc.controller.TestBedControllerList;
import org.testis.gui.mvc.controller.testbed.DutController;
import org.testis.gui.mvc.utilities.AtofValidationUtils;
import org.testis.gui.mvc.utilities.Validatable;
import org.testis.gui.mvc.utilities.ValidationUtils;
import org.testis.gui.mvc.view.AbstractViewPanel;
import org.testis.gui.mvc.view.AtofBaseDialog;
import org.testis.orm.testbed.refined.DeviceDefinitionFactory;
import org.testis.orm.testbed.refined.DeviceDefinitionRefined;
import org.testis.orm.testbed.refined.DeviceFirmwareRefined;
import org.testis.orm.testbed.refined.DutRefined;
import org.testis.orm.testbed.refined.SerialConnectionFactory;
import org.testis.orm.testbed.refined.SerialConnectionRefined;
import org.testis.orm.testbed.refined.TestPcFactory;
import org.testis.orm.testbed.refined.TestPcRefined;
import java.awt.Frame;
import java.awt.event.WindowListener;
import java.beans.PropertyChangeEvent;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;

/**
 *
 * @author selcuk
 */
public class DutView extends AtofBaseDialog implements
        AbstractViewPanel, Validatable {

    private DutController m_controller;
    private boolean m_editMode;
    private int m_dutId;
    private DutRefined m_dutRefined = null;

    /** Creates new form DutView */
    public DutView(Frame owner, boolean modal, boolean editMode) {
        super(owner, modal);
        m_controller = TestBedControllerList.newInstance().getDutController();
        m_editMode = editMode;
        initComponents();

        setFrameIcon("images/testbed/" + DutRefined.TYPE_NAME.toLowerCase(
                Locale.ENGLISH) + ".png");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        ipTextField = new javax.swing.JTextField();
        nameTextField = new javax.swing.JTextField();
        pcComboBox = new javax.swing.JComboBox();
        isSerialActiveComboBox = new javax.swing.JComboBox();
        deviceComboBox = new javax.swing.JComboBox();
        firmwareComboBox = new javax.swing.JComboBox();
        serialConfigComboBox = new javax.swing.JComboBox();
        saveButton = new javax.swing.JButton();
        closeButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(getWindowTitle());
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jLabel1.setText("Serial Config.");

        jLabel2.setText("TestBedIp ");

        jLabel3.setText("Pc");

        jLabel4.setText("Device");

        jLabel5.setText("Firmware ");

        jLabel6.setText("Name ");

        jLabel7.setText("IsSerialActive");

        pcComboBox.setModel(new DefaultComboBoxModel());
        populatePcComboBox();

        isSerialActiveComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "false", "true" }));
        isSerialActiveComboBox.setSelectedIndex(1);

        deviceComboBox.setModel(new DefaultComboBoxModel());
        populateDeviceComboBox();
        deviceComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deviceComboBoxActionPerformed(evt);
            }
        });

        firmwareComboBox.setModel(new DefaultComboBoxModel());
        populateFirmwareComboBox(getSelectedDevice());

        serialConfigComboBox.setModel(new DefaultComboBoxModel());
        populateSerialConfigComboBox();

        saveButton.setText("Save");
        setDefaultButton(saveButton);
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        closeButton.setText("Close");
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel5)
                            .addComponent(jLabel4)
                            .addComponent(jLabel6)
                            .addComponent(jLabel3)
                            .addComponent(jLabel7)
                            .addComponent(jLabel1))
                        .addGap(25, 25, 25)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(deviceComboBox, 0, 249, Short.MAX_VALUE)
                            .addComponent(firmwareComboBox, 0, 249, Short.MAX_VALUE)
                            .addComponent(nameTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE)
                            .addComponent(ipTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE)
                            .addComponent(serialConfigComboBox, javax.swing.GroupLayout.Alignment.TRAILING, 0, 249, Short.MAX_VALUE)
                            .addComponent(pcComboBox, 0, 249, Short.MAX_VALUE)
                            .addComponent(isSerialActiveComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(saveButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(closeButton)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {closeButton, saveButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pcComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel4)
                    .addComponent(deviceComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel5)
                    .addComponent(firmwareComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel6)
                    .addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel2)
                    .addComponent(ipTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(serialConfigComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(14, 14, 14)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(isSerialActiveComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(closeButton)
                    .addComponent(saveButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        WindowListener[] listeners = getWindowListeners();
        for (int i = 0; i < listeners.length; i++) {
            this.removeWindowListener(listeners[i]);
        }
        this.setVisible(false);
        this.setEnabled(false);
        m_controller.operationCloseWindow();
        this.dispose();
    }//GEN-LAST:event_formWindowClosed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        if (!validateForm()) {
            return;
        }
        saveButton.setEnabled(false);

        String name = nameTextField.getText();
        int deviceId = getSelectedDeviceId();
        int firmwareId = getSelectedFirmwareId();
        String testBedIp = ipTextField.getText();
        int serialId = getSelectedSerialConfigId();
        int pcId = getSelectedTestPcId();
        int dslamId = 1; // admin
        boolean isSerialActive = (isSerialActiveComboBox.getSelectedIndex() == 1);

        if (m_editMode) {
            HashMap values = new HashMap();
            values.put("dutId", m_dutId);
            values.put("deviceId", deviceId);
            values.put("activeFirmwareId", firmwareId);
            values.put("name", name);
            values.put("testBedIp", testBedIp);
            values.put("serialId", serialId);
            values.put("pcId", pcId);
            values.put("dslamId", dslamId);
            values.put("isSerialActive", isSerialActive);
            m_controller.operationSaveDut(m_dutRefined, values);
        } else {
            m_controller.operationAddDut(deviceId, firmwareId, name, testBedIp,
                    serialId, pcId, dslamId, isSerialActive);
        }
        dispose();
    }//GEN-LAST:event_saveButtonActionPerformed

    private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed
        dispose();
    }//GEN-LAST:event_closeButtonActionPerformed

    private void deviceComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deviceComboBoxActionPerformed
        populateFirmwareComboBox(getSelectedDevice());
    }//GEN-LAST:event_deviceComboBoxActionPerformed

    @Override
    public void modelPropertyChange(PropertyChangeEvent evt) {
        if (evt.getPropertyName().equals(
                DutController.VISIBLE_PROPERTY)) {
            this.centerParent();
        } else if (evt.getPropertyName().equals(
                DutController.DUT_REFINED_PROPERTY)) {
            DutRefined val = (DutRefined) evt.getNewValue();
            m_dutRefined = val;
        } else if (evt.getPropertyName().equals(
                DutController.DUT_ID_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            m_dutId = val;
        } else if (evt.getPropertyName().equals(
                DutController.TEST_PC_ID_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            selectPcCombobox(val);
        } else if (evt.getPropertyName().equals(
                DutController.DEVICE_ID_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            selectDeviceComboBox(val);
        } else if (evt.getPropertyName().equals(
                DutController.FIRMWARE_ID_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            selectFirmwareComboBox(val);
        } else if (evt.getPropertyName().equals(
                DutController.NAME_PROPERTY)) {
            String val = (String) evt.getNewValue();
            nameTextField.setText(val);
        } else if (evt.getPropertyName().equals(
                DutController.IP_PROPERTY)) {
            String val = (String) evt.getNewValue();
            ipTextField.setText(val);
        } else if (evt.getPropertyName().equals(
                DutController.SERIAL_ID_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            selectSerialConfigComboBox(val);
        } else if (evt.getPropertyName().equals(
                DutController.DSLAM_ID_PROPERTY)) {
        } else if (evt.getPropertyName().equals(
                DutController.SERIAL_ACTIVE_PROPERTY)) {
            selectSerialActiveComboBox((Boolean) evt.getNewValue());
        } else if (evt.getPropertyName().equals(
                DutController.ERROR_PROPERTY)) {
            String val = (String) evt.getNewValue();
            JOptionPane.showMessageDialog(
                    this,
                    val,
                    "Error Dialog",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    @Override
    public boolean validateForm() {
        boolean valid = true;
        StringBuilder builder = new StringBuilder();

        // check IP address is valid
        if (!ipTextField.getText().isEmpty() && !AtofValidationUtils.isValidIpAddress(
                ipTextField.getText())) {
            builder.append("Invalid IP address entered.\n");
            valid = false;
        }

        if (ValidationUtils.isEmpty(nameTextField.getText())) {
            builder.append("Name must not be empty.\n");
            valid = false;
        }

        if (!valid) {
            JOptionPane.showMessageDialog(null,
                    builder.toString(),
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
        return valid;
    }

    private void populatePcComboBox() {
        pcComboBox.removeAllItems();
        List<TestPcRefined> li = TestPcFactory.newInstance().getTestPcList();
        for (Iterator<TestPcRefined> it = li.iterator(); it.hasNext();) {
            pcComboBox.addItem(it.next());
        }
    }

    private void populateDeviceComboBox() {
        deviceComboBox.removeAllItems();
        List<DeviceDefinitionRefined> list = DeviceDefinitionFactory.newInstance().getDeviceList();
        for (Iterator<DeviceDefinitionRefined> it = list.iterator();
                it.hasNext();) {
            DeviceDefinitionRefined obj = it.next();
            deviceComboBox.addItem(obj);
        }
    }

    private void populateFirmwareComboBox(DeviceDefinitionRefined selectedDevice) {
        firmwareComboBox.removeAllItems();
        if (selectedDevice == null) {
            return;
        }
        List<DeviceFirmwareRefined> fwList = selectedDevice.getFirmwareList();
        Collections.sort(fwList);
        for (Iterator<DeviceFirmwareRefined> it = fwList.iterator();
                it.hasNext();) {
            firmwareComboBox.addItem(it.next());
        }
    }

    private void populateSerialConfigComboBox() {
        serialConfigComboBox.removeAllItems();
        List<SerialConnectionRefined> connections = SerialConnectionFactory.newInstance().getConnectionList();
        for (Iterator<SerialConnectionRefined> it = connections.iterator();
                it.hasNext();) {
            serialConfigComboBox.addItem(it.next());
        }
    }

    private int getSelectedTestPcId() {
        int result = 0;
        TestPcRefined obj = (TestPcRefined) pcComboBox.getSelectedItem();
        if (obj != null) {
            result = obj.getId();
        }
        return result;
    }

    private int getSelectedDeviceId() {
        int result = 0;
        DeviceDefinitionRefined device = getSelectedDevice();
        if (device != null) {
            result = device.getId();
        }
        return result;
    }

    private DeviceDefinitionRefined getSelectedDevice() {
        DeviceDefinitionRefined result = null;
        Object obj = deviceComboBox.getSelectedItem();
        if (obj != null) {
            result = (DeviceDefinitionRefined) obj;
        }
        return result;
    }

    private int getSelectedFirmwareId() {
        int result = 0;
        DeviceFirmwareRefined obj = (DeviceFirmwareRefined) firmwareComboBox.getSelectedItem();
        if (obj != null) {
            result = obj.getId();
        }
        return result;
    }

    private int getSelectedSerialConfigId() {
        int result = 0;
        SerialConnectionRefined obj = (SerialConnectionRefined) serialConfigComboBox.getSelectedItem();
        if (obj != null) {
            result = obj.getId();
        }
        return result;
    }

    private void selectPcCombobox(int testPcId) {
        DefaultComboBoxModel model = (DefaultComboBoxModel) pcComboBox.getModel();
        for (int i = 0; i < model.getSize(); i++) {
            TestPcRefined testPcRefined = (TestPcRefined) model.getElementAt(i);
            if (testPcRefined != null && testPcRefined.getId() == testPcId) {
                pcComboBox.setSelectedIndex(i);
                return;
            }
        }
    }

    private void selectDeviceComboBox(int deviceId) {
        DefaultComboBoxModel model = (DefaultComboBoxModel) deviceComboBox.getModel();
        for (int i = 0; i < model.getSize(); i++) {
            DeviceDefinitionRefined refined = (DeviceDefinitionRefined) model.getElementAt(
                    i);
            if (refined != null && refined.getId() == deviceId) {
                deviceComboBox.setSelectedIndex(i);
                return;
            }
        }
    }

    private void selectFirmwareComboBox(int id) {
        DefaultComboBoxModel model = (DefaultComboBoxModel) firmwareComboBox.getModel();
        for (int i = 0; i < model.getSize(); i++) {
            DeviceFirmwareRefined refined = (DeviceFirmwareRefined) model.getElementAt(
                    i);
            if (refined != null && refined.getId() == id) {
                firmwareComboBox.setSelectedIndex(i);
                return;
            }
        }
    }

    private void selectSerialConfigComboBox(int id) {
        DefaultComboBoxModel model = (DefaultComboBoxModel) serialConfigComboBox.getModel();
        for (int i = 0; i < model.getSize(); i++) {
            SerialConnectionRefined refined = (SerialConnectionRefined) model.getElementAt(
                    i);
            if (refined != null && refined.getId() == id) {
                serialConfigComboBox.setSelectedIndex(i);
                return;
            }
        }
    }

    private void selectSerialActiveComboBox(Boolean val) {
        if (val != null && val == Boolean.TRUE) {
            isSerialActiveComboBox.setSelectedIndex(1);
        } else {
            isSerialActiveComboBox.setSelectedIndex(0);
        }
    }

    private String getWindowTitle() {
        if (m_editMode) {
            return new String("Edit DUT");
        } else {
            return new String("Add New DUT");
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton closeButton;
    private javax.swing.JComboBox deviceComboBox;
    private javax.swing.JComboBox firmwareComboBox;
    private javax.swing.JTextField ipTextField;
    private javax.swing.JComboBox isSerialActiveComboBox;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JTextField nameTextField;
    private javax.swing.JComboBox pcComboBox;
    private javax.swing.JButton saveButton;
    private javax.swing.JComboBox serialConfigComboBox;
    // End of variables declaration//GEN-END:variables
}
